package com.tim.soundseechina;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;

public class HttpClientProc {
	static class Method {
		// GET请求
		public static final int GET = 0;
		// POST请求
		public static final int POST = 1;
	}

	/**
	 * get请求获取URL资源.
	 * 
	 * @param url
	 *            url地址.
	 * @return String 页面资源字符串.
	 */
	public static String getUrl2String(String url, String charSet) {
		// 创建一个客户端，类似打开一个浏览器
		HttpClient httpclient = new HttpClient();
		// 设置请求字符串
		httpclient.getParams().setContentCharset(charSet);
		// 创建一个get方法，类似在浏览器地址栏中输入一个地址
		GetMethod method = new GetMethod(url);
		try {
			httpclient.executeMethod(method);
			return method.getResponseBodyAsString();
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			method.releaseConnection();
		}
		return null;
	}

	/**
	 * get方法获取URL文件资源.
	 * 
	 * @param url
	 *            url地址.
	 * @param savePath
	 *            文件保存地址.
	 */
	public static void getUrl2File(String url, String savePath) {
		// 创建一个客户端，类似打开一个浏览器
		HttpClient httpclient = new HttpClient();
		// 创建一个get方法，类似在浏览器地址栏中输入一个地址
		GetMethod method = new GetMethod(url);
		InputStream input = null;
		FileOutputStream fos = null;
		try {
			httpclient.executeMethod(method);
			// 获取请求内容AsString.
			input = method.getResponseBodyAsStream();
			File file = new File(savePath);
			File dirs = file.getParentFile();
			if (!dirs.exists()) {
				dirs.mkdirs();
			}
			file.createNewFile();
			fos = new FileOutputStream(file);
			byte[] data = new byte[1024 * 5];
			int len = 0;
			// 有时未到文件尾会读出-1？费解!Debug过
			while ((len = input.read(data)) > 0) {
				fos.write(data, 0, len);
			}
			fos.flush();
			fos.close();
			input.close();
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			method.releaseConnection();
		}
	}

	public static String getUrl2String(String url, String charSet, int method) {
		if (method == Method.GET) {
			return getUrl2String(url, charSet);
		} else {
			HttpClient client = new HttpClient();
			// 设置请求字符串
			client.getParams().setContentCharset(charSet);
			PostMethod post = null;
			if (url.indexOf("?") != -1) {
				post = new PostMethod(url.substring(0, url.indexOf("?")));
				// 获取请求参数
				url = url.substring(url.indexOf("?") + 1);
				String[] paramsArr = url.split("&");
				for (int i = 0; i < paramsArr.length; i++) {
					// 请求参数名
					String paramName = paramsArr[i].substring(0, paramsArr[i].indexOf("="));
					// 请求参数值
					String paramValue = paramsArr[i].substring(paramsArr[i].indexOf("=") + 1);
					post.addParameter(paramName, paramValue);
				}
			} else {
				post = new PostMethod(url);
			}
			try {
				client.executeMethod(post);
				return post.getResponseBodyAsString();
			} catch (HttpException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}
	}

	public static void uploadFile() {
		String targetURL = null;// TODO 指定URL
		File targetFile = null;// TODO 指定上传文件

		targetFile = new File("1.mp3");
		targetURL = "http://localhost:8080/test/tt"; // servleturl
		PostMethod filePost = new PostMethod(targetURL);
		try {
			// 通过以下方法可以模拟页面参数提交
			// filePost.setParameter("name", "中文");
			// filePost.setParameter("pass", "1234");

			Part[] parts = { new FilePart(targetFile.getName(), targetFile) };
			filePost.setRequestEntity(new MultipartRequestEntity(parts,
					filePost.getParams()));
			HttpClient client = new HttpClient();
			client.getHttpConnectionManager().getParams().setConnectionTimeout(
					5000);
			int status = client.executeMethod(filePost);
			if (status == HttpStatus.SC_OK) {
				System.out.println("上传成功");
			} else {
				System.out.println("上传失败");
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			filePost.releaseConnection();
		}
	}
}
